import { ElNotification } from 'element-plus'
import store from 'store'

// import vuex from '@/store/index'
import API_LIST from '@/config/api.config'
import base from '@/config/base.config'
import { useUser } from '@/store/user'
import encrypt from '@/unit/encrypt'

import serve from './common'
const { TOKEN_NAME } = base
export default async function $http({ type = 'index', data } = {}) {
  let user = useUser()
  if (!(type in API_LIST)) {
    return new Error('请求方法不对')
  }

  try {
    let { RASsend, url, method, rest, isSetToken } = API_LIST[type]
    // 如果是get请求, 将第二个参数config中设置params 为data, 设置到url上
    method = method.toLowerCase()

    if (rest === true) {
      // 将:后面的内容切出来, 对应this中传进来的键
      let restName = url.match(/:(.*)$/)[1]
      // 将发送的请求:后面, 替换为数据
      url = url.replace(/:(.*)$/, data[restName]).trim()
    }

    // 可以手动query内容放入路由中, 也可以使用axios传参方式
    // eslint-disable-next-line no-param-reassign
    data = method === 'get' ? { params: data } : data
    // 如果加密条件为 true, 对data进行加密
    if (RASsend && data[RASsend]) {
      data[RASsend] = await encrypt(data[RASsend])
    }
    let result = await serve[method]?.(url, data)
    if (isSetToken === true) {
      store.set('uid', result.data.userId)
      store.set(TOKEN_NAME, result.data.token)
      await user.login()
    }
    return result
  } catch (err) {
    if (err.response) {
      let message = err.response.data.message
      console.warn('错误信息:' + message)
      if (type !== 'index') {
        // 由于将http作为插件(挂载Vue的prototype上), 在调用http时, this指向Vue,
        ElNotification.error({
          title: '错误',
          message,
        })
      }
    }
    return Promise.reject(err)
  }
}
